package com.zxr.diana.web.server;

import com.zxr.diana.web.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * @author xuerui.zhang
 * @since 2019-06-17 19:46
 */
public class TomcatServer {

    private Tomcat tomcat;
    private String[] args;

    public TomcatServer(String[] args) {
        this.args = args;
    }

    public void start() throws LifecycleException {
        tomcat = new Tomcat();
        tomcat.setPort(8080);
        tomcat.start();

        //Tomcat 与 Servlet 建立联系
        Context context = new StandardContext();
        context.setPath("");
        context.addLifecycleListener(new Tomcat.FixContextListener());

        DispatcherServlet servlet = new DispatcherServlet();
        Tomcat.addServlet(context, "dispatcherServlet", servlet).setAsyncSupported(true);
        context.addServletMappingDecoded("/", "dispatcherServlet");

        tomcat.getHost().addChild(context);

        //让Tomcat一直连接
        Thread tomcatAwait = new Thread(() -> TomcatServer.this.tomcat.getServer().await(), "tomcat_await");
        tomcatAwait.setDaemon(false);
        tomcatAwait.start();
    }
}
